package com.self.campussecondhandmarket.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.campussecondhandmarket.entity.domain.Goods;
import com.self.campussecondhandmarket.entity.domain.Orders;
import com.self.campussecondhandmarket.entity.request.goods.Inventory;
import com.self.campussecondhandmarket.entity.request.orders.Cancel;
import com.self.campussecondhandmarket.entity.request.orders.CreateOrders;
import com.self.campussecondhandmarket.entity.request.orders.Good;
import com.self.campussecondhandmarket.mapper.OrdersMapper;
import com.self.campussecondhandmarket.resp.Result;
import com.self.campussecondhandmarket.service.GoodsService;
import com.self.campussecondhandmarket.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 31465
 * @description 针对表【tb_orders(订单表)】的数据库操作Service实现
 * @createDate 2024-04-13 11:38:46
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
		implements OrdersService {
	
	@Autowired
	private GoodsService goodsService;
	
	
	/*
	 * @Description: 创建订单
	 * @Param: [dto]
	 * @return: com.self.campussecondhandmarketapplication.resp.Result<java.lang.String>
	 **/
	@Override
	@Transactional
	public Result<String> createOrders(CreateOrders dto) {
		Orders orders = new Orders();
		String json = dto.getGood();
		System.out.println(json);
		Good good1 = JSONObject.parseObject(json, Good.class);
		orders.setUserId(dto.getUserid());
		orders.setPrice(good1.getPrice());
		orders.setTotalPrice(dto.getTotalPrice());
		orders.setStatus(dto.getStatus());
		orders.setAddress(dto.getAddress());
		orders.setRemark(dto.getBeizhu());
		orders.setQuantity(good1.getQuantity());
		orders.setPick(0);
		orders.setGoodsId(dto.getGoodsId());
		orders.setOrdersNo(System.currentTimeMillis());
		this.baseMapper.insert(orders);
		goodsService.changeInventory(new Inventory(dto.getGoodsId(), good1.getQuantity()));
		return Result.success("创建订单成功");
	}
	
	@Override
	@Transactional
	public Result<String> cancel(Cancel dto) {
		// 取消订单
		this.baseMapper.update(Wrappers.<Orders>lambdaUpdate()
				.eq(Orders::getId, dto.getOrdersId())
				.set(Orders::getStatus, dto.getStatus())
		);
		// 还原库存
		Goods goods = goodsService.getById(dto.getGoodsId());
		goodsService.update(Wrappers.<Goods>lambdaUpdate()
				.eq(Goods::getId, dto.getGoodsId())
				.set(Goods::getNum, goods.getNum() + dto.getQuantity())
		);
		return Result.success("订单已取消");
	}
	
	@Override
	public void changeStatus(Integer ordersId, Integer status) {
		this.baseMapper.update(Wrappers.<Orders>lambdaUpdate()
				.eq(Orders::getId, ordersId)
				.set(Orders::getStatus, status)
		);
	}
}




